//
//  InAppPurchaseManager.m
//  Autismus
//
//  Created by Jean-Élie Le Corre on 15/01/12.
//  Copyright (c) 2012 RedShift. All rights reserved.
//

#import "InAppPurchaseManager.h"
#import "BMAAppManager.h"

@implementation InAppPurchaseManager

@synthesize delegate;

//STEP1 - Requesting product info
- (void)requestProUpgradeProductData
{
    if ([SKPaymentQueue canMakePayments])
	{
        NSLog(@"Retrieve Info");
		//Retreive product info
		SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"com.auticiel.autimo.premium"]];	
		request.delegate = self;
		[request start];
	}
    else
    {
        UIAlertView *alertPayment = [[UIAlertView alloc] initWithTitle:@"Erreur" message:@"Vous avez désactivé les achats au sein de cette application. Veuillez réactiver cette fonctionnalité afin d'effectuer l'achat de la version pro. Merci." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[alertPayment show];
		[alertPayment release];
    }
}

//STEP2 - Showing product info & create payment
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
	NSArray *invalidProduct = response.invalidProductIdentifiers;
    
    NSLog(@"Information received");
	if ([invalidProduct count] == 0) {
		// Creating payment
		NSArray *myProduct = response.products;
        NSLog(@"Creating payment for product : %@", [[myProduct objectAtIndex:0] productIdentifier]);
		SKPayment *payment = [SKPayment paymentWithProductIdentifier:[[myProduct objectAtIndex:0] productIdentifier]];
		[[SKPaymentQueue defaultQueue] addPayment:payment];
	}
    else
    {
        for (NSString *invalidProductId in response.invalidProductIdentifiers)
            NSLog(@"Invalid product id: %@" , invalidProductId);
    }
    
}

//STEP3 - Payment response
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
	NSLog(@"Payment queue");
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
                
                //Transaction purchased	
            case SKPaymentTransactionStatePurchased:
                NSLog(@"Transaction purchased");
                [self completeTransaction:transaction];
                break;
                
                //Transaction failed
            case SKPaymentTransactionStateFailed:
                NSLog(@"Transaction failed");
				[self failedTransaction:transaction];
                break;
                
                //Transaction restored
            case SKPaymentTransactionStateRestored:
                NSLog(@"Transaction restored");
				[self restoreTransaction:transaction];
				break;
				
            default:
                break;
        }
    }
}

//STEP4a - Complete the transaction
- (void)completeTransaction: (SKPaymentTransaction *)transaction {
    NSLog(@"Complete transaction");
    [self recordTransaction:transaction];
    [self provideContent:transaction.payment.productIdentifier];
	// Remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

//STEP4b - Restore a previous transaction not completed
- (void)restoreTransaction: (SKPaymentTransaction *)transaction {    
    NSLog(@"Restore transaction");
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
    // Method called when user trying to restore the product already bought
    // Method to restore -> [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    // Here we just have to provide the content if its the right transaction of course :p
    // The SKPaymentTransaction object has the info to compare
}

//STEP4c - Transaction failed
- (void)failedTransaction: (SKPaymentTransaction *)transaction {
    NSLog(@"Failed Transaction");
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        UIAlertView *alertPayment = [[UIAlertView alloc] initWithTitle:@"Erreur" message:@"La transaction a échoué" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[alertPayment show];
		[alertPayment release];
    }
    NSLog(@"Error");
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

//STEP5 - Record transaction
- (void)recordTransaction:(SKPaymentTransaction *)transaction {
	// Store the transaction on our servers
    // Not mandatory
}

//STEP6 - Provide payed content
- (void)provideContent:(NSString *)productIdentifier {
    NSLog(@"Provide content");
    
    // Here put the code to unlock the two games
    // Change the value enabled for the desired games
    // cf plist
    BMAAppManager *manager = [BMAAppManager sharedInstance];
    [manager unlockPremiumVersion];
    if (delegate && [delegate respondsToSelector:@selector(initGames)]) {
        [delegate initGames];
    }
}

@end
